<template>
  <n-modal
    :show="showModal"
    preset="dialog"
    title="请输入激活码"
    positive-text="确定"
    negative-text="取消"
    @positive-click="handleActive"
    @negative-click="handleClose"
    @close="handleClose"
  >
    <n-form
      ref="formRef"
      :label-width="80"
      :model="formValue"
      :rules="rules"
      size="small"
    >
      <n-form-item path="code">
        <n-input v-model:value.trim="formValue.code" placeholder="输入激活码" />
      </n-form-item>
    </n-form>
  </n-modal>
</template>

<script setup lang="ts">
import { createUserActiveExam } from '@/api/userActiveExam'
import type { FormInst } from 'naive-ui'
import { useMessage } from 'naive-ui'
const formRef = ref<FormInst | null>(null)
const message = useMessage()

const props = withDefaults(
  defineProps<{
    examId: string
    showModal: boolean
  }>(),
  {
    showModal: false
  }
)

const emits = defineEmits<{
  (e: 'close'): void
}>()

const rules = {
  code: {
    required: true,
    message: '请输入激活码',
    trigger: 'blur'
  }
}

const formValue = reactive({
  code: ''
})

const handleActive = () => {
  formRef.value?.validate((errors) => {
    if (!errors) {
      // 激活
      createUserActiveExam({
        examId: props.examId,
        activeCode: formValue.code.trim()
      })
        .then(() => {
          message.success('激活成功')
          emits('close')
        })
        .catch((err) => {
          // message.error('err')
        })
    } else {
      console.log(errors)
      message.error('表单格式有误')
    }
  })
}

const handleClose = () => {
  emits('close')
}
</script>

<style scoped lang="scss"></style>
